package com.jiuyue.movehouse.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiuyue.movehouse.common.exception.BadRequestException;
import com.jiuyue.movehouse.entity.Car;
import com.jiuyue.movehouse.entity.CarType;
import com.jiuyue.movehouse.mapper.CarMapper;
import com.jiuyue.movehouse.mapper.CarTypeMapper;
import com.jiuyue.movehouse.service.CarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yourFather
 * @since 2022-02-12
 */
@Service
@AllArgsConstructor
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {

    private CarTypeMapper carTypeMapper;

    @Override
    public Page<Car> getCarList(Page<Car> page, Car car) {
        Page<Car> carPage = this.page(page, Wrappers.<Car>lambdaQuery()
                .like(StrUtil.isNotEmpty(car.getCarNumber()), Car::getCarNumber, car.getCarNumber())
                .eq(!Objects.isNull(car.getCarTypeId()), Car::getCarTypeId, car.getCarTypeId())
                .eq(!Objects.isNull(car.getState()), Car::getState, car.getState())
        );
        for (Car record : page.getRecords()) {
            record.setCarTypeName(carTypeMapper.selectById(record.getCarTypeId()).getName());
        }
        return carPage;
    }

    @Override
    public void saveCar(Car car) {
        checkCarNumber(car);
        this.save(car);
    }

    @Override
    public void updateCar(Car car) {
        checkCarNumber(car);
        deleteCheck(car.getId());
        this.updateById(car);
    }

    @Override
    public void deleteCar(Long carId) {
        deleteCheck(carId);
        this.removeById(carId);
    }

    private void checkCarNumber(Car car) {
        if (this.count(Wrappers.<Car>lambdaQuery().eq(Car::getCarNumber, car.getCarNumber()).ne(Objects.nonNull(car.getId()),Car::getId,car.getId())) > 0) {
            throw new BadRequestException(car.getCarNumber() + "已存在");
        }
    }

    private void deleteCheck(Long carId) {
        Car old = this.getById(carId);
        if (old.getState().equals(1)) {
            throw new BadRequestException(old.getCarNumber() + "正在使用中不能删除");
        }
    }
}
